using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BuffVulnerability:BuffBase {
	public override string spriteName => "vulnerability";

	public BuffVulnerability(BuffSlot slot,Mob mob) : base(slot,mob) {
		mark=Object.Instantiate(vulnerableMarkPrefab,mob.transform);
		RandomizeMarkPosition();
	}

	static GameObject _vulnerableMarkPrefab;
	static GameObject vulnerableMarkPrefab =>
	_vulnerableMarkPrefab ?
	_vulnerableMarkPrefab :
	Resources.Load<GameObject>("VulnerableMarkPrefab");

	static EventSubscriber<DamageEventArgs> mobDamageSubscriber = new EventSubscriber<DamageEventArgs>();
	static BuffVulnerability() {
		Mob.Damaging+=mobDamageSubscriber.TargetEventHandler;
	}

	GameObject mark;
	void RandomizeMarkPosition() {
		Bounds bound = mob.collider.bounds;
		Vector2 newPosition = new Vector2(
		Random.Range(bound.min.x,bound.max.x),
		Random.Range(bound.min.y,bound.max.y)
		);
		mark.transform.position=newPosition;
	}

	protected override void OnRemove() {
		base.OnRemove();
		Object.Destroy(mark);
	}

	protected override void SubscribeEvents() {
		base.SubscribeEvents();
		mobDamageSubscriber.SubscribeSingle(mob,Mob_Damaging);
	}
	protected override void UnsubscribeEvents() {
		base.UnsubscribeEvents();
		mobDamageSubscriber.UnsubscribeSingle(mob,Mob_Damaging);
	}
	void Mob_Damaging(object sender,DamageEventArgs e) {

		if(!e.stat.attackerProjectile) return;
		Projectile attackerProjectile = e.stat.attackerProjectile;
		Vector2 position = attackerProjectile.transform.position;
		Vector2 velocityNormal = attackerProjectile.velocity;
		velocityNormal=new Vector2(velocityNormal.y,-velocityNormal.x);
		Vector2 offset = (Vector2)mark.transform.position-position;

		const float tolerance = 0.2f;
		if(velocityNormal.sqrMagnitude==0) {
			if(offset.magnitude>tolerance) return;
		} else {
			velocityNormal.Normalize();
			float distance = Mathf.Abs(Vector2.Dot(velocityNormal,offset));
			if(distance>tolerance) return;
		}
		e.stat.amount.AddMultiply(1.5f,float.MaxValue);
		e.stat.crit=true;
		stacks-=1;
		if(stacks<=0) {
			RemoveSelf();
		}
		RandomizeMarkPosition();
	}

	protected override void Update() {
		base.Update();
		if(stacks<=0) {
			RemoveSelf();
		}
	}


}